#ifndef TIMER_H
#define TIMER_H

#include <stdint.h>
#include "mhscpu.h"

#define FCLK						((*((volatile uint32_t*)(0x4001F02C)))*1000)

typedef struct SysTick_MemMap{
	uint32_t CSR;
	uint32_t RVR;
	uint32_t CVR;
	uint32_t CALIB;
}volatile *SysTick_MemMapPtr;

#define SysTick_BASE_PTR			((SysTick_MemMapPtr)0xE000E010u)

#define	BEGIN_TEST()				{\
										SysTick_BASE_PTR->CVR = 0;\
										SysTick_BASE_PTR->RVR = 15000000;\
										SysTick_BASE_PTR->CSR = (1 << 2) | (1 << 0);\
									}\

#define END_TEST()					{\
										dbg_t = SysTick_BASE_PTR->CSR & 0x10000 ? SysTick_BASE_PTR->RVR : 0;\
										dbg_t += SysTick_BASE_PTR->RVR - SysTick_BASE_PTR->CVR;\
										SysTick_BASE_PTR->CSR = 0;\
									}\

static __inline void mh_dbg_time_begin(void)
{
	SysTick_BASE_PTR->CVR = 0;
	SysTick_BASE_PTR->RVR = 15000000;
	SysTick_BASE_PTR->CSR = (1 << 2) | (1 << 0);
}

static __inline uint32_t mh_dbg_time_get(void)
{
	uint32_t dbg_t;
	dbg_t = SysTick_BASE_PTR->CSR & 0x10000 ? SysTick_BASE_PTR->RVR : 0;
	dbg_t += SysTick_BASE_PTR->RVR - SysTick_BASE_PTR->CVR;
	SysTick_BASE_PTR->CSR = 0;
	return dbg_t;
}

static __inline uint32_t mh_dbg_fclk_get(void)
{
	return FCLK;
}


void timer_init(void);
void timer_init_ms(uint32_t ms);

void timer_start(uint32_t num);
void timer_pause(uint32_t num);
void timer_stop(void);
uint32_t timer_tick(uint32_t num);
uint32_t timer_counter(void);
uint32_t timer_us(uint32_t num,  uint32_t ms_per, uint32_t pclk_fre);


#endif
